<?php

namespace app\admin\controller;

use app\admin\exception\AdminException;
use app\common\entity\Export;
use app\common\entity\Image;
use app\common\entity\ServiceInfo;
use app\common\entity\Video;
use app\common\shop\ArticleCateModel;
use think\Db;
use think\Request;
use app\common\entity\User;
use app\common\entity\PersonService;

class Article extends Admin
{
    /**
     * @power 客服工单类表
     * @rank 4
     */
    public function person(Request $request)
    {
        $query = PersonService::alias('ps')->field('ps.*,u.mobile');

        if ($status = $request->get('status')) {
            $query->where('ps.status', $status);
            $map['status'] = $status;
        }

        $startTime = $request->get('startTime');
        $endTime = $request->get('endTime');
        if($startTime && $endTime){
            $query->where('ps.create_time', '<', strtotime($endTime))
                ->where('ps.create_time', '>=', strtotime($startTime));
            $map['startTime'] = $startTime;
            $map['endTime'] = $endTime;
        }

        $list = $query
            ->leftJoin('user u','ps.uid = u.id')
            ->order('id desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        // echo $query->getLastSql();
        return $this->render('personService', [
            'list' => $list,
            'entry' => new User(),
        ]);
    }
    /**
     * @power 拒绝客服工单
     * @rank 4
     */
    public function refuseperson(Request $request)
    {
        $id = $request->param('id');
        $reply = $request->post('reply');
        if(!$id || !$reply){
            return json(['code'=>1,'message'=>'拒绝理由不能为空']);
        }
        $res = PersonService::where('id',$id)->update([
            'status' => 2,
            'reply' => $reply,
        ]);

        if($res){
            //LogService::write('工单管理', '用户通过充值申请列表');
            return json(['code'=>0,'message'=>'操作失败']);
        }
        return json(['code'=>1,'message'=>'操作失败']);
    }
    /**
     * @power 通过客服工单
     * @rank 4
     */
    public function passPerson(Request $request)
    {
        $id = $request->param('id');
        $low = PersonService::where('id',$id)->update([
            'status' => 2,
            'reply' => '已通过',
        ]);
        if($low){
            return json(['code'=>0,'toUrl'=>url('personService')]);
        }
        return json(['code' => 1, 'message' => '操作失败']);
    }
    /**
     * [文章分类]
     * @param
     * @return
     */
    public function cate( Request $request ){
        $cate = new ArticleCateModel();
        $map = $request->param();
        $list = $cate->paginate(15, false, [
            'query' => isset($map) ? $map : []
        ]);

        return $this->render('cate', [
            'list' => $list,
            'cate' => \app\common\entity\Article::getAllCate()
        ]);
    }
    /**
     * [添加分类]
     * @param
     * @return
     */
    public function addcate( Request $request ){
        return $this->render('cateedit');

    }
    /**
     * [获取审核状态]
     * @param
     * @return
     */
    public function cateedit( Request $request ){
        return $this->render('cateedit',['info'=>ArticleCateModel::where('id',input('id'))->find()]);
    }
    /**
     * [添加分类保存]
     * @param
     * @return
     */
    public function catesave( Request $request ){
        $input = input();
        if(!$input['title']) return json()->data(['code'=>1,'message'=>'名称不能为空']);
        ArticleCateModel::dispose($input);
        return json(['code' => 0, 'toUrl' => url('/admin/article/cate')]);
        //return json(['code' => 0, 'message' => '添加成功']);
    }
    /**
     * [添加分类保存]
     * @param
     * @return
     */
    public function cateupdate( Request $request ){
        $input = input();
        if(!$input['title']) return json()->data(['code'=>1,'message'=>'名称不能为空']);
        ArticleCateModel::dispose($input,input('id'));
        return json(['code' => 0, 'toUrl' => url('/admin/article/cate')]);
        //return json(['code' => 0, 'message' => '修改成功']);
    }
    /**
     * [删除分类]
     * @param
     * @return
     */
    public function catedelete( Request $request ){
        $id = input('id');
        $info = ArticleCateModel::where('id',$id)->find();
        if(empty($info)) return json()->data(['code'=>1,'message'=>'数据错误，请刷新重试']);
        $info->delete();
        return json(['code' => 0, 'toUrl' => url('/admin/article/cate')]);
    }
    /**
     * @power 内容管理|文章管理
     * @rank 5
     */
    public function index(Request $request)
    {
        $entity = \app\common\entity\Article::field('*');
        if ($cate = $request->get('type')) {
            $entity->where('category', $cate);
            $map['type'] = $cate;
        }

        $list = $entity->paginate(15, false, [
            'query' => isset($map) ? $map : []
        ]);

        return $this->render('index', [
            'list' => $list,
            'cate' => \app\common\entity\Article::getAllCate(),
            'acate'=>ArticleCateModel::order('id asc')->select(),
        ]);
    }

    /**
     * @power 内容管理|文章管理@添加文章
     */
    public function create()
    {
        return $this->render('edit', [
            'acate'=>ArticleCateModel::order('id asc')->select(),
            'cate' => \app\common\entity\Article::getAllCate()
        ]);
    }

    /**
     * @power 内容管理|文章管理@编辑文章
     */
    public function edit($id)
    {

        $Article = new \app\common\entity\Article();
        $entity = $Article->where('article_id', $id)->find();
        if (!$entity) {
            $this->error('用户对象不存在');
        }

        return $this->render('edit', [
            'acate'=>ArticleCateModel::order('id asc')->select(),
            'info' => $entity,
            'cate' => \app\common\entity\Article::getAllCate()
        ]);
    }

    /**
     * @power 内容管理|文章管理@添加文章
     */
    public function save(Request $request)
    {
        $res = $this->validate($request->post(), 'app\admin\validate\Article');

        if (true !== $res) {
            return json()->data(['code' => 1, 'message' => $res]);
        }
        if (!$request->post('content')) {
            return json()->data(['code' => 1, 'message' => '内容不能为空']);
        }

        $service = new \app\common\entity\Article();
        $result = $service->addArticle($request->post());

        if (!$result) {
            throw new AdminException('保存失败');
        }
        //添加用户提醒
        if ($request->post('category') == 1 && $request->post('status') == 1) {
//            User::update(['notice' => 1], ['notice' => 0]);
        }

        return json(['code' => 0, 'toUrl' => url('/admin/article')]);
    }

    /**
     * @power 内容管理|文章管理@编辑文章
     */
    public function update(Request $request, $id)
    {

        $res = $this->validate($request->post(), 'app\admin\validate\Article');

        if (true !== $res) {
            return json()->data(['code' => 1, 'message' => $res]);
        }


        $entity = $this->checkInfo($id);

        $service = new \app\common\entity\Article();
        $result = $service->updateArticle($entity, $request->post());

        if (!$result) {
            throw new AdminException('保存失败');
        }

        return json(['code' => 0, 'toUrl' => url('/admin/article')]);
    }

    /**
     * 导出留言
     */
    public function exportMessage(Request $request)
    {
        $export = new Export();
        $entity = \app\common\entity\Message::field('m.*,u.mobile, u.nick_name')->alias('m');
        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'mobile':
                    $entity->where('u.mobile', $keyword);
                    break;
                case 'nick_name':
                    $entity->where('u.nick_name', $keyword);
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }
        $list = $entity->leftJoin("user u", 'm.user_id = u.id')
            ->order('m.create_time', 'desc')
            ->select();
        $filename = '留言列表';
        $header = array('会员昵称', '会员账号', '内容', '提交时间');
        $index = array('nick_name', 'mobile', 'content', 'create_time');
        $export->createtable($list, $filename, $header, $index);
    }

    /**
     * @power 内容管理|文章管理@删除文章
     */
    public function delete(Request $request, $id)
    {
        $entity = $this->checkInfo($id);

        if (!$entity->delete()) {
            throw new AdminException('删除失败');
        }

        return json(['code' => 0, 'message' => 'success']);
    }

    private function checkInfo($id)
    {
        $entity = \app\common\entity\Article::where('article_id', $id)->find();
        if (!$entity) {
            throw new AdminException('对象不存在');
        }

        return $entity;
    }

    /**
     * @power 内容管理|反馈列表
     * @method GET
     */
    public function messageList(Request $request)
    {
        $entity = \app\common\entity\Message::field('m.*,u.mobile, u.nick_name')->alias('m');
        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'mobile':
                    $entity->where('u.mobile', $keyword);
                    break;
                case 'nick_name':
                    $entity->where('u.nick_name', $keyword);
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }
        $list = $entity->leftJoin("user u", 'm.user_id = u.id')
            ->order('m.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        return $this->render('messageList', [
            'list' => $list
        ]);
    }

    /**
     * 回复留言
     */
    public function replyMsg(Request $request)
    {
        $id = $request->post("id");
        $uid = $request->post("user_id");
        $content = $request->post("content");
        if (trim($content) == '') {
            return json(['code' => 1, 'message' => '请输入回复内容']);
        }
        //内容
        $data['content'] = $content;
        $data['message_id'] = $id;
        $data['create_time'] = time();
        $data['user_id'] = $uid;

        $res = \app\common\entity\MessageReply::insert($data);
        if ($res) {
            \app\common\entity\Message::update(['status' => 2], ['message_id' => $id]);
            return json(['code' => 0]);
        } else {
            return json(['code' => 1, 'message' => '回复失败']);
        }

    }

    /**
     * @power 内容管理|反馈列表@删除留言
     * @method GET
     */
    public function deleteMsg(Request $request)
    {
        $entity = \app\common\entity\Message::where("message_id", $request->get("id"))->delete();
        return json(['code' => 0, 'toUrl' => url('/admin/article/messageList')]);
    }

    #客服信息列表
    public function serviceList()
    {
        $list = ServiceInfo::select();
        return $this->render('servicelist', [
            'list' => $list
        ]);
    }

    #内容管理|客服信息编辑
    public function serviceedit(Request $request)
    {
        $id = $request->param('id');
        $list = ServiceInfo::where('id', $id)->find();

        return $this->render('serviceedit', [
            'info' => $list
        ]);
    }

    #客服信息修改
    public function updservice(Request $request)
    {
        $id = $request->param('id');
        $name = $request->post('name');

        $wx = $request->post('wx');
        $qq = $request->post('qq');
        $data = [
            'name' => $name,
            'wx' => $wx,
            'create_time' => time(),
            'qq'=>$qq
        ];

        $updphoto = ServiceInfo::where('id', $id)->update($data);
        if ($updphoto) {

            return json(['code' => 0, 'message' => '修改成功', 'toUrl' => url('admin/article/servicelist')]);

        }

        return json(['code' => 1, 'message' => '修改失败']);

    }

    #内容管理|客服信息添加
    public function serviceadd()
    {
        return $this->render('serviceedit');
    }

    #客服信息添加
    public function saveservice(Request $request)
    {

        $name = $request->post('name');
        $wx = $request->post('wx');

        $data = [
            'name' => $name,
            'wx' => $wx,
            'create_time' => time()
        ];

        $insphoto = ServiceInfo::insert($data);

        if ($insphoto) {

            return json(['code' => 0, 'message' => '添加成功', 'toUrl' => url('admin/article/servicelist')]);

        }

        return json(['code' => 1, 'message' => '添加失败']);

    }

    #客服信息删除
    public function servicedel(Request $request)
    {

        $uid = $request->param('id');

        $del = ServiceInfo::where('id', $uid)->delete();

        if ($del) {

            return json(['code' => 0, 'message' => '删除成功']);

        }

        return json(['code' => 1, 'message' => '删除失败']);

    }


    #内容管理|图片列表
    public function image()
    {
        $list = Image::select();
        return $this->render('imagelist', [
            'list' => $list,
            'model' => new Image()
        ]);
    }

    #内容管理|图片添加
    public function imageadd()
    {
        return $this->render('imageedit',['types' => Image::getAllCate()]);
    }

    #图片添加
    public function saveimage(Request $request)
    {

        $photo = $request->post('photo');
        $title = $request->post('title');
        $sort = $request->post('sort');
        $types = $request->post('types');
        $click_num = $request->post('click_num');
        $url = $request->post('url');

        $data = [
            'pic' => $photo,
            'title' => $title,
            'sort' => $sort,
            'url' => $url,
            'types' => $types,
            'click_num' => $click_num,
            'create_time' => time(),
            'update_time' => time(),
        ];

        $insphoto = Image::insert($data);

        if ($insphoto) {

            return json(['code' => 0, 'message' => '添加成功', 'toUrl' => url('article/image')]);

        }

        return json(['code' => 1, 'message' => '添加失败']);

    }

    #内容管理|图片编辑
    public function imageedit(Request $request)
    {
        $id = $request->param('id');
        $list = Image::where('id', $id)->find();

        return $this->render('imageedit', [
            'info' => $list,
            'types' => Image::getAllCate()
        ]);
    }

    #图片修改
    public function updimage(Request $request)
    {
        $id = $request->param('id');
        $title = $request->post('title');

        $photo = $request->post('photo');
        $sort = $request->post('sort');
        $types = $request->post('types');
        $url = $request->post('url');
        $click_num = $request->post('click_num');


        $data = [
            'pic' => $photo,
            'sort' => $sort,
            'title' => $title,
            'types' => $types,
            'url' => $url,
            'click_num' => $click_num,
            'update_time' => time()
        ];

        $updphoto = Image::where('id', $id)->update($data);
        if ($updphoto) {

            return json(['code' => 0, 'message' => '修改成功', 'toUrl' => url('article/image')]);

        }

        return json(['code' => 1, 'message' => '修改失败']);

    }

    #图片删除
    public function imagedel(Request $request)
    {

        $uid = $request->param('id');

        $del = Image::where('id', $uid)->delete();

        if ($del) {

            return json(['code' => 0, 'message' => '删除成功']);

        }

        return json(['code' => 1, 'message' => '删除失败']);

    }





    #内容管理|视频列表
    public function video()
    {
        $list = Video::select();
        return $this->render('videolist', [
            'list' => $list,
            'model' => new Video()
        ]);
    }

    #内容管理|视频添加
    public function videoadd()
    {
        return $this->render('videoedit');
    }

    #视频添加
    public function savevideo(Request $request)
    {

        $photo = $request->post('photo');
        $title = $request->post('title');
        $sort = $request->post('sort');
        $click_num = $request->post('click_num');
        $url = $request->post('url');
        $ts = $request->post('ts');

        $data = [
            'pic' => $photo,
            'title' => $title,
            'sort' => $sort,
            'url' => $url,
            'click_num' => $click_num,
            'create_time' => time(),
            'update_time' => time(),
            'ts' => $ts,
        ];

        $insphoto = Video::insert($data);

        if ($insphoto) {

            return json(['code' => 0, 'message' => '添加成功', 'toUrl' => url('article/video')]);

        }

        return json(['code' => 1, 'message' => '添加失败']);

    }

    #内容管理|视频编辑
    public function videoedit(Request $request)
    {
        $id = $request->param('id');
        $list = Video::where('id', $id)->find();

        return $this->render('videoedit', [
            'info' => $list
        ]);
    }

    #视频修改
    public function updvideo(Request $request)
    {
        $id = $request->param('id');
        $title = $request->post('title');

        $photo = $request->post('photo');
        $sort = $request->post('sort');
        $url = $request->post('url');
        $click_num = $request->post('click_num');
        $ts = $request->post('ts');


        $data = [
            'pic' => $photo,
            'sort' => $sort,
            'title' => $title,
            'url' => $url,
            'click_num' => $click_num,
            'update_time' => time(),
            'ts' => $ts,
        ];

        $updphoto = Video::where('id', $id)->update($data);
        if ($updphoto) {

            return json(['code' => 0, 'message' => '修改成功', 'toUrl' => url('article/video')]);

        }

        return json(['code' => 1, 'message' => '修改失败']);

    }

    #视频删除
    public function videodel(Request $request)
    {

        $uid = $request->param('id');

        $del = Video::where('id', $uid)->delete();

        if ($del) {

            return json(['code' => 0, 'message' => '删除成功']);

        }

        return json(['code' => 1, 'message' => '删除失败']);

    }


    /**
     * @power 帮助中心
     */
    public function help()
    {
        $entity = Db::name('help')->where('id', 1)->find();

        if (!$entity) {
            $this->error('用户对象不存在');
        }
        return $this->render('help', [
            'info' => $entity,
        ]);
    }
    /**
     * @power 帮助中心
     */
    public function edit_help(Request $request)
    {
        $entity = Db::name('help')->where('id', 1)->update($request->post());
        if ($entity) {
            return json(['code' => 0,  'message' =>'修改成功']);
        }else {
            $this->error('修改失败');
            return json(['code' => 0, 'message' =>'修改失败']);
        }
    }


}
